<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="./css/bootstrap.min.css" />
    <style>
      .form-select {
        width: 103px;
        display: inline-block;
      }

      .col-form-label {
        text-align: right;
      }

      .figure-img {
        width: 100px;
        height: 100px;
      }

      #upload {
        display: none;
      }

      .figure-caption {
        cursor: pointer;
      }
    </style>
  </head>

  <body>
    <div class="container">
      <h1 class="p-5">个人设置</h1>
      <form class="col-6">
        <div class="row mb-3">
          <label class="col-form-label col-3">用户名：</label>
          <div class="col-7">
            <input id="username" disabled class="form-control col-9" type="text" />
          </div>
        </div>
        <div class="row mb-3">
          <label class="col-form-label col-3">籍贯：</label>
          <div class="col-9">
            <select class="form-select col-4" name="province">
              <option value="">--省--</option>
            </select>
            <select class="form-select col-4" name="city">
              <option value="">--市--</option>
            </select>
            <select class="form-select col-4" name="county">
              <option value="">--县--</option>
            </select>
          </div>
        </div>
        <div class="row mb-3">
          <label class="col-form-label col-3">头像：</label>
          <div class="col-9">
            <figure class="figure">
              <input type="file" id="upload" />
              <img src="./imgs/default.jpg" class="figure-img img-fluid rounded" alt="..." />
              <figcaption class="figure-caption">修改头像</figcaption>
            </figure>
          </div>
        </div>
        <div class="row mb-3">
          <label class="col-3"></label>
          <div class="col-9">
            <button class="btn btn-primary">保存</button>
          </div>
        </div>
      </form>
    </div>

    <script src="./lib/bootstrap.min.js"></script>
    <script src="./lib/axios.js"></script>
    <script src="./lib/form-value.js"></script>
    <script src="./lib/request.js"></script>
    <script>
      // 获取页面元素
      let provinceSelect = document.querySelector('[name=province]')
      let citySelect = document.querySelector('[name=city]')
      let countySelect = document.querySelector('[name=county]')
      let form = document.querySelector('form')
      let fileInput = document.querySelector('#upload')
      let btn = document.querySelector('figcaption')
      let img = document.querySelector('img')
      let username = document.querySelector('#username')

      // 封装渲染省市县的函数
      function render(select, text, data) {
        let arr = [`<option value="">--${text}--</option>`]
        data.forEach(item => arr.push(`<option value="${item}">${item}</option>`))
        select.innerHTML = arr.join('')
      }

      // 发送请求，获取个人信息
      // 初始化省市县
      ;(async function () {
        // 省
        let { data: province } = await axios.get('/api/province')
        render(provinceSelect, '省', province)
        // 市
        provinceSelect.addEventListener('change', async function () {
          let { data: city } = await axios.get('/api/city', { params: { pname: this.value } })
          render(citySelect, '市', city)
        })
        // 县
        citySelect.addEventListener('change', async function () {
          let { data: county } = await axios.get('/api/county', {
            params: { pname: provinceSelect.value, cname: this.value }
          })
          render(countySelect, '县', county)
        })
      })()
      ;(async function () {
        const {
          data: { data: res }
        } = await axios.get('/user/info')
        // console.log(res)
        if (res.province && res.city && res.county) {
          // 获取用户所在省中全部的市，渲染到下拉框
          let request1 = axios.get('/api/city', { params: { pname: res.province } })
          // 获取用户所在市中全部的县，渲染到下拉框
          let request2 = axios.get('/api/county', {
            params: { pname: res.province, cname: res.city }
          })
          const [{ data: city }, { data: county }] = await Promise.all([request1, request2])
          // console.log(city)
          render(citySelect, '市', city)
          // console.log(county)
          render(countySelect, '县', county)
          val(document.querySelector('form'), res)
        }
        if (res.avatar) img.src = res.avatar
        username.value = res.username
      })()
      // 点击保存，提交省市县
      form.addEventListener('submit', async function (e) {
        e.preventDefault()
        // console.log(val(this))
        const { data: res } = await axios.post('/user/info', val(this))
        if (res.status === 0) {
          alert(res.message)
        }
      })
      // 点击按钮，选文件
      btn.addEventListener('click', () => fileInput.click())
      // 文件域改变，上传头像
      fileInput.addEventListener('change', async function () {
        if (this.files.length > 0) {
          let fileObj = this.files[0]
          img.src = URL.createObjectURL(fileObj)
          let fd = new FormData()
          fd.append('avatar', fileObj)
          const { data: res } = await axios.post('/user/avatar', fd)
          if (res.status === 0) alert(res.message)
        }
      })
    </script>
  </body>
</html>
